from django.http import JsonResponse, Http404
from django.utils.deprecation import MiddlewareMixin
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response

from gesture_demo_server.common.result import BaseResponse, ResultCode


class HandleRequestException(MiddlewareMixin):
    @staticmethod
    def process_exception(request=None, exception=Exception("未知异常")):
        api = request.get_full_path() if request is not None else 'None'
        ret = "请求错误, 请稍后再试"
        # logger_error.info("API: %s\n 异常信息:%s " % (api, exception))  # 还可以捕获异常, 写到错误日志里边, 测试阶段直接把exception返回就可以
        # return BaseResponse(code=ResultCode.CODE_SERVER_ERROR, message='服务器内部错误')
        response = BaseResponse(code=ResultCode.CODE_SERVER_ERROR, message=f'服务器内部错误: {exception}')
        # render时需要的几个属性，初始化时赋上默认值，不然内部raise错误时会响应异常
        response.accepted_renderer = JSONRenderer()
        response.accepted_media_type = 'application/json'
        response.renderer_context = {}
        return response
